<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllOrders, getOrderById, cancelOrder } from '../../api/order'

// 定义类型
interface Payment {
  paymentID: number
  amount: number
  paymentMethod: string
  isPaid: boolean
}

interface Room {
  roomID: number
  roomType: string
  price: number
  status: string
  hotel?: {
    name: string
    address: string
  }
}

interface User {
  userId: number
  username: string
  email: string
}

interface Order {
  orderID: number
  userId: number
  roomID: number
  checkInDate: string
  checkOutDate: string
  user?: User
  room?: Room
  payments?: Payment[]
}

// 订单列表数据
const orderList = ref<Order[]>([])
// 加载状态
const loading = ref(false)
// 订单详情对话框显示控制
const detailDialogVisible = ref(false)
// 当前查看的订单详情
const currentOrderDetail = ref<Order | null>(null)
// 订单详情加载状态
const detailLoading = ref(false)

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true
    const res = await getAllOrders()
    orderList.value = res.data
  } catch (error) {
    console.error('获取订单列表失败', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchOrders()
})

// 格式化日期显示
const formatDate = (dateString: string) => {
  if (!dateString) return '--'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 查看订单详情
const handleViewDetail = async (row: Order) => {
  try {
    detailLoading.value = true
    detailDialogVisible.value = true
    const res = await getOrderById(row.orderID)
    currentOrderDetail.value = res.data
  } catch (error) {
    console.error('获取订单详情失败', error)
    ElMessage.error('获取订单详情失败')
    detailDialogVisible.value = false
  } finally {
    detailLoading.value = false
  }
}

// 取消订单
const handleCancelOrder = (row: Order) => {
  ElMessageBox.confirm('确定要取消该订单吗？此操作将不可逆', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await cancelOrder(row.orderID)
      ElMessage.success('取消订单成功')
      fetchOrders() // 刷新列表
    } catch (error: any) {
      ElMessage.error(error.message || '取消订单失败')
    }
  }).catch(() => {
    // 取消操作，不做任何处理
  })
}

// 计算订单状态
const getOrderStatus = (order: Order) => {
  const now = new Date()
  const checkInDate = new Date(order.checkInDate)
  const checkOutDate = new Date(order.checkOutDate)
  
  if (now < checkInDate) {
    return '待入住'
  } else if (now >= checkInDate && now <= checkOutDate) {
    return '入住中'
  } else {
    return '已完成'
  }
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const map: Record<string, string> = {
    '待入住': 'warning',
    '入住中': 'success',
    '已完成': 'info'
  }
  return map[status] || 'info'
}

// 计算订单总价
const calculateTotalPrice = (order: Order) => {
  if (!order || !order.room) return 0
  
  const checkInDate = new Date(order.checkInDate)
  const checkOutDate = new Date(order.checkOutDate)
  const days = Math.ceil((checkOutDate.getTime() - checkInDate.getTime()) / (1000 * 60 * 60 * 24))
  
  return days * order.room.price
}
</script>

<template>
  <div class="orders-container">
    <div class="page-header">
      <h2>订单管理</h2>
    </div>
    <div class="orders-list">
      <el-table 
        :data="orderList" 
        style="width: 100%" 
        v-loading="loading"
        border
      >
        <el-table-column prop="orderID" label="订单ID" width="80" />
        <el-table-column label="用户信息" width="120">
          <template #default="scope">
            {{ scope.row.user?.username || '未知用户' }}
          </template>
        </el-table-column>
        <el-table-column label="酒店/房间" min-width="180">
          <template #default="scope">
            <div>
              <p>{{ scope.row.room?.hotel?.name || '未知酒店' }}</p>
              <p class="room-type">{{ scope.row.room?.roomType || '未知房型' }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="入住日期" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.checkInDate) }}
          </template>
        </el-table-column>
        <el-table-column label="离店日期" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.checkOutDate) }}
          </template>
        </el-table-column>
        <el-table-column label="价格" width="120">
          <template #default="scope">
            <span class="price">¥{{ scope.row.room?.price || 0 }}/晚</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(getOrderStatus(scope.row))">
              {{ getOrderStatus(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleViewDetail(scope.row)">详情</el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleCancelOrder(scope.row)"
              :disabled="getOrderStatus(scope.row) !== '待入住'"
            >取消</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="600px"
      destroy-on-close
    >
      <div v-loading="detailLoading">
        <template v-if="currentOrderDetail">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="订单编号">{{ currentOrderDetail.orderID }}</el-descriptions-item>
            <el-descriptions-item label="用户信息">{{ currentOrderDetail.user?.username }}</el-descriptions-item>
            <el-descriptions-item label="用户邮箱">{{ currentOrderDetail.user?.email }}</el-descriptions-item>
            <el-descriptions-item label="酒店名称">{{ currentOrderDetail.room?.hotel?.name }}</el-descriptions-item>
            <el-descriptions-item label="酒店地址">{{ currentOrderDetail.room?.hotel?.address }}</el-descriptions-item>
            <el-descriptions-item label="房间类型">{{ currentOrderDetail.room?.roomType }}</el-descriptions-item>
            <el-descriptions-item label="房间单价">¥{{ currentOrderDetail.room?.price }}/晚</el-descriptions-item>
            <el-descriptions-item label="入住日期">{{ formatDate(currentOrderDetail.checkInDate) }}</el-descriptions-item>
            <el-descriptions-item label="离店日期">{{ formatDate(currentOrderDetail.checkOutDate) }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="getStatusTagType(getOrderStatus(currentOrderDetail))">
                {{ getOrderStatus(currentOrderDetail) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="订单总价">
              <span class="total-price">¥{{ calculateTotalPrice(currentOrderDetail) }}</span>
            </el-descriptions-item>
          </el-descriptions>

          <div class="payment-info" v-if="currentOrderDetail.payments && currentOrderDetail.payments.length > 0">
            <h3>支付信息</h3>
            <el-table :data="currentOrderDetail.payments" border>
              <el-table-column prop="paymentID" label="支付ID" width="80" />
              <el-table-column prop="amount" label="金额" width="120">
                <template #default="scope">
                  ¥{{ scope.row.amount }}
                </template>
              </el-table-column>
              <el-table-column prop="paymentMethod" label="支付方式" width="150" />
              <el-table-column prop="isPaid" label="支付状态" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.isPaid ? 'success' : 'warning'">
                    {{ scope.row.isPaid ? '已支付' : '未支付' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="no-payment" v-else>
            <el-empty description="暂无支付记录"></el-empty>
          </div>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.orders-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.orders-list {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.room-type {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.total-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.payment-info {
  margin-top: 20px;
}

.payment-info h3 {
  font-size: 16px;
  margin-bottom: 10px;
  font-weight: normal;
  color: #606266;
}

.no-payment {
  margin-top: 20px;
}
</style> 